package com.qidian.buy.mq;

import com.qidian.buy.service.ItemService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
*@author 戴着假发的程序员
*@company 起点编程
*@date 2023/9/15 11:40
*/
@Component // 将我们的监听者交给spring
public class ItemAddReceive implements ChannelAwareMessageListener {
    @Autowired
    private ItemService itemService;
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 获取消息的唯一性ID
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        Long itemId = null;
        try {
            String msg = new String(message.getBody(),"UTF-8");
            System.out.println(msg);
            try {
                itemId = new Long(msg);
            } catch (NumberFormatException e) {
                // 拒绝策略
                channel.basicReject(deliveryTag, false);
                throw new RuntimeException(e);
            }
            // 手动确认
            channel.basicAck(deliveryTag,true);
            itemService.genDetailStatic(itemId);
        } catch (IOException e) {
            // 重试.....
            throw new RuntimeException(e);
        }
    }
}
